﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.NewPhotoRindGrid;
using MINERP.DAL.NewPhotoRindGrid;
using MINERP.MODEL.FoundationModel;
using MINERP.COM;
using MINERP.DAL;

namespace MINERP.BLL.NewPhotoRindGrid
{
    /// <summary>
    /// 处理整个与分片相关的业务逻辑
    /// </summary>
    public class MainBLL
    {
        GridDAL_Grid _gridDal;

        /// <summary>
        /// 根据相应的分区ID得到对应的格子里的所有信息
        /// </summary>
        /// <param name="subAreaId"></param>
        /// <returns></returns>
        public int GetGridInfoBySubAreaId(int subAreaId, out List<GridInfo_Grid> GridInfo_GridList)
        {
           return  GetHasProductGridInfoBySubAreaId(subAreaId, out GridInfo_GridList, 1);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="subAreaId"></param>
        /// <param name="GridInfo_GridList"></param>
        /// <param name="isAll">1:全部包括空格子，2：只取有信息的</param>
        /// <returns></returns>
        public int GetHasProductGridInfoBySubAreaId(int subAreaId, out List<GridInfo_Grid> GridInfo_GridList,int isAll)
        {
            int result = 0;
            List<Grid_Info> GridBaseInfoList;
            OrderInfo_Grid oG = null;
            GridInfo_Grid ginfo = null;
            OrderInfoBLL_Grid orderBLL;
 
            GridInfo_GridList = null;

            if (subAreaId > 0)
            {
                GridInfo_GridList = new List<GridInfo_Grid>();
                orderBLL = new OrderInfoBLL_Grid();

                _gridDal = new GridDAL_Grid();

                result = _gridDal.GetGridInfoBySubAreaId(subAreaId, out GridBaseInfoList,isAll);

                if (GridBaseInfoList == null || GridBaseInfoList.Count < 1)
                {
                    result = 2;//只有分区头，没有格子信息
                }
                if (result == 1)
                {
                    result = 3;
                }

                if (result == 0)
                {
                    foreach (var gridBaseInfo in GridBaseInfoList)
                    {
                        ginfo = new GridInfo_Grid() { GridBaseInfo = gridBaseInfo };

                        //分别出得相应的OrderInfo_Grid、PhotoInfo_Info
                        if (gridBaseInfo.SomeId != 0)
                        {
                            try
                            {
                                if (orderBLL.GetOrderInfo_Grid(gridBaseInfo.SomeId, out oG) == 0)
                                {
                                    ginfo.OrderInfo = oG;
                                }
                            }
                            catch (Exception)
                            {
                                ginfo.OrderInfo = null;
                            }
                       
                        }
                        GridInfo_GridList.Add(ginfo);
                    }
                }
            }
            else
            {
                result = 1;
            }


            return result;
        }

        /// <summary>
        /// 分配格子
        /// </summary>
        /// <param name="photoBarcode"></param>
        /// <param name="IsPrint">是否需要打印</param>
        /// <param name="gridId">格子ID</param>
        /// <param name="ginfo">如果为NULL是说明是旧的的格子，如果不为空，则说明是新格子</param>
        /// <returns>1:操作成功</returns>
        public int AssignGrid(string photoBarcode, out bool IsPrint, out int gridId, int curSubAreaId, int uid, out GridInfo_Grid ginfo, out string strNextTechName)
        {
            int result = 1;
            int orderProductId = 0;
            int parentOrderProductId = 0;
            int checkIsOverOrderProductId = 0;//用来检查是否完成的产品ID
            int photoId = 0;
            int techId = 0;

            strNextTechName = "";//如果分片完成，下一个流程节点的名称

            bool isNewGrid = false;//是否分配的是新格子
            bool isReBackOrder = false;//此照片是否为返单照片
            bool isCompleted = false;//分片是否完成

            gridId = 0;
            IsPrint = false;
            ginfo = null;//如果分配的是一个新格子，则用此变量来存储相关的信息 

            Grid_Info AssinGInfo = null;
            OrderFlowListStatus curTechStatus;

            PhotoBLL_Grid _photoBll = new PhotoBLL_Grid();
            OrderInfoBLL_Grid _orderBll = new OrderInfoBLL_Grid();
            GridBLL_Grid _gridBLL = new GridBLL_Grid();

            result = _photoBll.CheckIsReBackOrder(photoBarcode, out orderProductId, out photoId, out parentOrderProductId);
            if (result == 2)//正常单
            {
                #region 正常单
                checkIsOverOrderProductId = orderProductId;

                result = _gridBLL.AssignGridByForOrderProductId(orderProductId, out isNewGrid, curSubAreaId, out AssinGInfo);
                if (result == 1)//成功
                {
                    gridId = AssinGInfo.GridId;
                    _photoBll.UpdatePhotoStatus(photoId, PhotoStatus.FenPian);

                    if (isNewGrid)//新格子,需要初始化一些东东
                    {
                        ginfo = ConvertGinfoToGridinfo_Grid(AssinGInfo);
                    }
                }
                #endregion
            }
            else if (result == 3)//返单
            {
                #region 返单
                isReBackOrder = true;
                //得到父产品的状态,主要是流程状态
                result = _orderBll.GetTechIdByOrderProductId(parentOrderProductId, out techId, out curTechStatus);
                if (result == 1)//成功
                {
                    if (techId > 8)
                    {
                        checkIsOverOrderProductId = orderProductId;
                        #region 父产品已过本结点,所有操作就是对子产品进行
                        result = _gridBLL.AssignGridByForOrderProductId(orderProductId, out isNewGrid, curSubAreaId, out AssinGInfo);
                        if (result == 1)//分配成功
                        {
                            gridId = AssinGInfo.GridId;
                            //只改变照片的状态，不改变条码，条码在子产品分片完成时一起批量改（即子产品的照片都改条码）
                            _photoBll.UpdatePhotoStatus(photoId, PhotoStatus.FenPian);//只改变此照片的状态为分片，只有当此子产品全部完成时，子产品中的照片才能再次返单
                            if (isNewGrid)
                            {
                                ginfo = ConvertGinfoToGridinfo_Grid(AssinGInfo);
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        checkIsOverOrderProductId = parentOrderProductId;
                        #region//父产品未过本结点,以父单的名义分配格子，并且子产品都已完成，这里不需要考虑子产品的完成问题
                        result = _gridBLL.AssignGridByForOrderProductId(parentOrderProductId, out isNewGrid, curSubAreaId, out AssinGInfo);
                        if (result == 1)//成功
                        {
                            gridId = AssinGInfo.GridId;
                            _photoBll.UpdatePhotoBarCode(photoId);

                            if (isNewGrid)//新格子,需要初始化一些东东
                            {
                                ginfo = ConvertGinfoToGridinfo_Grid(AssinGInfo);
                            }
                        }
                        #endregion
                    }
                }
                #endregion
            }

            //检查此照片所对应的产品的所有照片是否都分片完成
            if (result == 1)
            {
                result = _orderBll.CheckOrderPhotoAssignCompleted(checkIsOverOrderProductId, out isCompleted);
                if (result == 1)
                {
                    if (isCompleted)
                    {
                        result = _orderBll.OverOrderFlow(checkIsOverOrderProductId, isReBackOrder, uid, out strNextTechName);
                        //清空Grid表的相关的信息
                        _gridBLL.ClearGrid(gridId);
                        if (result == 1)
                        {
                            IsPrint = true;
                        }
                    }
                }
            }

            return result;
        }

        public int AssignGridByPhotoCode(string photoBarCode, out int IsPrint, out int gridId, int curSubAreadId, int opUid, out GridInfo_Grid gViewInfo, out string strNextTechName, int curTechId, out bool isNewGrid, out int orderProductId, out string shopGridName, bool isAutoAssignShop, out string outProductOrderInBag,out string outShopName)
        {
            int result = 1;
            IsPrint = 0;
            gridId = 0;
            gViewInfo = null;
            strNextTechName = string.Empty;
            shopGridName = string.Empty;
            orderProductId = 0;
            outProductOrderInBag = string.Empty;
            outShopName = string.Empty;
            isNewGrid=false;

            int photoId = ConvertBarCodeToId(photoBarCode);
            if (photoId==0)
            {
                return -1;//输入的参数有误；
            }

            GridDAL_Grid _gridDal = new GridDAL_Grid();
            GridBLL_Grid _gridBll=new GridBLL_Grid ();

            result = _gridDal.AssignGridForPhoto(photoId, (int)SubAreaType.Photo, curSubAreadId, out isNewGrid, out IsPrint, out strNextTechName, out gridId, opUid, curTechId, out orderProductId, out shopGridName, isAutoAssignShop, out outProductOrderInBag,out outShopName);
            if (result==1)
            {
                if (isNewGrid)
                {
                    gViewInfo = _gridBll.GetGridViewInfoByGridId(gridId, orderProductId);
                }
            }
            return result;
        }
       
        //将条码转换为ID
        private int ConvertBarCodeToId(string strBarCode)
        {
            if (strBarCode.Length == 10)
            {
                try
                {
                    return Convert.ToInt32(strBarCode.Substring(1));
                }
                catch (Exception)
                {
                    return 0;
                }

            }
            return 0;
        }

        /// <summary>
        /// 当格子的数据库的实体转化为实现需要的实体
        /// </summary>
        /// <param name="ginfo"></param>
        /// <returns></returns>
        private GridInfo_Grid ConvertGinfoToGridinfo_Grid(Grid_Info ginfo)
        {
            OrderInfoBLL_Grid _orderBll = new OrderInfoBLL_Grid();
            PhotoBLL_Grid _photoBll = new PhotoBLL_Grid();
            GridInfo_Grid ginfo_Grid = new GridInfo_Grid();
            OrderInfo_Grid oG = null;

            ginfo_Grid.GridBaseInfo = ginfo;
            if (_orderBll.GetOrderInfo_Grid(ginfo.SomeId, out oG) == 0)
            {
                int rel = 0;
                oG.PhotoS = _photoBll.GetPhotosByOrderProductId(ginfo.SomeId, out rel);

                ginfo_Grid.OrderInfo = oG;
            }

            return ginfo_Grid;
        }


        /// <summary>
        /// 清空选中的格子
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int ClearSelectedGrid(List<GridInfo_Grid> list)
        {
            int resul = 1;
            using (newSampleYPDBEntities db=new newSampleYPDBEntities ())
            {
                //1.将GRID的状态 =0 someid=0
                //2.改变PHOTO的状态

                Grid g = null;
                orderInfo o = null;
                foreach (var ginfo in list)
                {
                    g = db.Grid.FirstOrDefault(gd => gd.GridId == ginfo.GridBaseInfo.GridId);
                    if (g!=null)
                    {
                        o = db.orderInfo.FirstOrDefault(oi => oi.OrderProductId == ginfo.OrderInfo.OrderProductId);
                        if (o!=null)
                        {
                            g.SomeId = 0;
                            g.Status = (int)GridStatus.useAble;

                            if (!o.photoInfo.IsLoaded)
                            {
                                o.photoInfo.Load();
                            }
                            foreach (var pi in o.photoInfo.ToList().Where(p=>p.status==(int)PhotoStatus.FenPian).ToList())
                            {
                                pi.status = (int)PhotoStatus.Printed;
                            }
                        }
                    }
                }
                try
                {
                    db.SaveChanges();
                }
                catch (Exception)
                {
                    resul = -1;
                }
              
            }

            return resul;
        }

        //将这些格子对应的还未出的照片进行清柜（特殊加急处理）
        public int PriorityGrid(List<GridInfo_Grid> list)
        {
            //对photostattus=1(正在拼板)，改变photo.status2=1
            //photo.status=2(已拼板)，改变photo.status2=1,改变对应大板的加急级别为最高11级
           
            if (list.Count>0)
            {
                GridDAL_Grid _gridDal = new GridDAL_Grid();
               return  _gridDal.PriorityGrid(list.Select(g => g.OrderInfo.OrderProductId).ToList());
            }

            return -1;

        }

        public string GetGridSubAreasNameBYGridID(int inGridID,int inPhtotId,out Boolean isComplete,out string GridName)
        {
            isComplete = false;
            string SubAreasName = "";
            GridName = "";
            //_gridDal = new GridDAL_Grid();
            //return _gridDal.GetSubGridNameByGridId(inGridID);
            using (newSampleYPDBEntities db = new newSampleYPDBEntities())
            {
                Grid grid = db.Grid.FirstOrDefault(p=>p.GridId==inGridID);
                grid.GridSubAreaReference.Load();
                SubAreasName = grid.GridSubArea.SubAreaName;
                photoInfo photo = db.photoInfo.FirstOrDefault(ph => ph.photoId == inPhtotId);
                photo.orderInfoReference.Load();

                photo.orderInfo.photoInfo.Load();
                photoInfo photoLeft = photo.orderInfo.photoInfo.FirstOrDefault(pho=>pho.status!=4);
                if (photoLeft == null)
                {
                    isComplete = true;
                   
                }
                GridName = grid.GridName;

            }
            return SubAreasName;
        }

        /// <summary>
        /// 分片完成是否直接分堆
        /// </summary>
        /// <returns></returns>
        public bool IsAutoAssignShop()
        {
            bool ret =false;
            try
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    WorkShop workshop = db.WorkShop.FirstOrDefault();
                    if (workshop != null)
                    {
                        ret = workshop.AutoAssignShop;
                    }
                }
            }
            catch
            {
                
            }

            return ret;
        }
    }
}
